#!/usr/bin/python
# -*- coding: utf-8 -*-

from flask_restful import Resource
from flask         import redirect,request,make_response,abort

from urllib.parse import parse_qs, urlparse

from e4ting       import log,util
from e4ting.api   import CasDoor

from config       import FlaskConf

class WebAuth(Resource):
    ''' 登录 '''
    #----------------------------------------------------------------------
    def __init__(self):
        super(WebAuth, self).__init__()

    def init(self):
        self.Method = request.headers.get("X-Original-Method")
        self.Uri    = request.headers.get("X-Original-Uri")

        self.Url    = request.headers.get("X-Original-Href")
        self.Ip     = request.headers.get("X-Real-Ip")

        self.Host   = request.headers.get("Host")

        self.code   = parse_qs(urlparse(self.Url).query).get("code", [None])[0]
        self.token  = request.headers.get("token", None) or request.headers.get("Authorization", None)

        log.info("Method={self.Method},Uri={self.Uri},Url={self.Url},Ip={self.Ip},Host={self.Host},code={self.code},token={self.token}".format(self=self))

    def verify_code(self, cas):
        if self.token:
            return
        if not self.code:
            return
        if not cas.check_code(code=self.code, refer=self.Url, client_ip=self.Ip):
            # code 校验没通过，如果通过里面会交换token
            abort(401)
        self.token = cas.code_swap_token(self.code)

    def get(self, **kwargs):
        self.init()
        cas = CasDoor(casdoor_host=FlaskConf.CASDOOR_HOST, client_id=FlaskConf.CASDOOR_ID, client_secret=FlaskConf.CASDOOR_SECRET)
        self.verify_code(cas)

        if not self.token:
            return {"code":401},401

        log.info(self.token)
        if not cas.check_token(self.token):
            # token 校验不通过
            return {"code":401},401

        return {"code":200}

    def post(self, *args, **kwargs):
        '''
            验证用户名密码
        '''
        return {
            "code"  : 200,
            "data"  : "登录成功",
            # "uuid"  : "admin",
            # "token" : ret,
            # "name"  : user,
            # "msg"   : "登录成功",
        }

